package abd.pr1.Controllers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import abd.pr1.Interface.LoginWindow;
import abd.pr1.Interface.MainWindow;
import abd.pr1.Mappers.UsuariosMapper;
import abd.pr1.Models.Usuario;

public class LoginController implements ActionListener {
	
	private LoginWindow loginWindow;
	private DataSource ds;
	
	public LoginController(LoginWindow login,DataSource ds){
		this.loginWindow=login;
		this.ds=ds;
		this.loginWindow.addListener(this);
	}

	
	@Override
	public void actionPerformed(ActionEvent e) {
		
		String nick = loginWindow.getUsuario();
		String password = loginWindow.getPassword();
		
		if (e.getActionCommand().equals("login")){
			
			Usuario userP= new Usuario(null, nick, password, null, null);
			List<Usuario> lu = new ArrayList<Usuario>();

			lu = new UsuariosMapper(this.ds).queryByExample(userP);
			
			if(lu.size()>0){
				loginWindow.dispose();
				new MainWindowController(new MainWindow(), ds, lu.get(0));
			} else {
				JOptionPane.showMessageDialog(null, "Usuario incorrecto");
			}
			
		} else if(e.getActionCommand().equals("nuevo_usuario")){
			File imagendefecto= new File("src/abd/pr1/Interface/silueta.gif");
			byte[] b = new byte[(int) imagendefecto.length()];
			
			FileInputStream fileInputStream;
			try {
				fileInputStream = new FileInputStream(imagendefecto);
				fileInputStream.read(b);
				fileInputStream.close();
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
            
			
			Usuario newUser= new Usuario(null, nick, password, null, b);
			
			List<Usuario> lu = new ArrayList<Usuario>();

			if((new UsuariosMapper(this.ds).insert(newUser))){
				loginWindow.dispose();
				new MainWindowController(new MainWindow(), ds, newUser);
			} else {
				JOptionPane.showMessageDialog(null, "Datos no validos");
			}
			
			
		}
	}

}
